-- ============================================
-- BLACKJACK - ComputerCraft / CC:Tweaked
-- Nécessite : Advanced Computer + Advanced Monitor (couleur)
-- ============================================

local SUITS = {
    { id = "H", symbol = "\3", color = colors.red },   -- coeur
    { id = "D", symbol = "\4", color = colors.red },   -- carreau
    { id = "C", symbol = "\5", color = colors.black }, -- trefle
    { id = "S", symbol = "\6", color = colors.black }, -- pique
}
local RANKS = { "2","3","4","5","6","7","8","9","10","J","Q","K","A" }

local MISE = 1
local points = 100

local mon = peripheral.find("monitor")
if not mon then
    error("Aucun monitor trouve ! Colle un Advanced Monitor a cote du computer.")
end

mon.setTextScale(0.5)
local prevTerm = term.redirect(mon)
local w, h = term.getSize()

local function centerText(y, text, textColor, bgColor)
    term.setBackgroundColor(bgColor or colors.black)
    term.setTextColor(textColor or colors.white)
    local x = math.floor((w - #text) / 2) + 1
    term.setCursorPos(x, y)
    term.write(text)
end

-- === DECK ===
local deck = {}

local function buildDeck()
    deck = {}
    for _, suit in ipairs(SUITS) do
        for _, rank in ipairs(RANKS) do
            table.insert(deck, { rank = rank, suit = suit })
        end
    end
    -- melange (Fisher-Yates)
    for i = #deck, 2, -1 do
        local j = math.random(1, i)
        deck[i], deck[j] = deck[j], deck[i]
    end
end

local function drawFromDeck()
    if #deck == 0 then buildDeck() end
    return table.remove(deck)
end

local function cardRankValue(rank)
    if rank == "A" then return 11 end
    if rank == "J" or rank == "Q" or rank == "K" then return 10 end
    return tonumber(rank)
end

local function handValue(hand)
    local total = 0
    local aces = 0
    for _, card in ipairs(hand) do
        total = total + cardRankValue(card.rank)
        if card.rank == "A" then aces = aces + 1 end
    end
    while total > 21 and aces > 0 do
        total = total - 10
        aces = aces - 1
    end
    return total
end

-- === AFFICHAGE DES CARTES ===
local CARD_W, CARD_H = 6, 5

local function drawCard(x1, y1, card, hidden)
    local x2, y2 = x1 + CARD_W - 1, y1 + CARD_H - 1
    if hidden then
        term.setBackgroundColor(colors.blue)
        term.setTextColor(colors.lightBlue)
        for y = y1, y2 do
            term.setCursorPos(x1, y)
            term.write(string.rep(" ", CARD_W))
        end
        centerText(y1 + 2, "???", colors.lightBlue, colors.blue)
        return
    end

    term.setBackgroundColor(colors.white)
    for y = y1, y2 do
        term.setCursorPos(x1, y)
        term.write(string.rep(" ", CARD_W))
    end

    term.setTextColor(card.suit.color)
    term.setBackgroundColor(colors.white)
    term.setCursorPos(x1 + 1, y1 + 1)
    term.write(card.rank)
    term.setCursorPos(x1 + 2, y1 + 2)
    term.write(card.suit.symbol)
    term.setCursorPos(x2 - #card.rank, y2 - 1)
    term.write(card.rank)
end

local function drawHand(hand, y, hideSecond)
    local n = #hand
    local totalWidth = n * (CARD_W + 1) - 1
    local x = math.max(1, math.floor((w - totalWidth) / 2) + 1)
    for i, card in ipairs(hand) do
        local hide = hideSecond and i == 2
        drawCard(x, y, card, hide)
        x = x + CARD_W + 1
    end
end

-- === BOUTONS ===
local buttons = {}

local function drawButton(index, label, x1, x2, y, bg)
    term.setBackgroundColor(bg)
    term.setTextColor(colors.white)
    for x = x1, x2 do
        term.setCursorPos(x, y)
        term.write(" ")
    end
    local lx = x1 + math.floor(((x2 - x1 + 1) - #label) / 2)
    term.setCursorPos(lx, y)
    term.write(label)
    buttons[index] = { x1 = x1, x2 = x2, y = y, name = label }
end

local playerY = h - 8
local dealerY = 6

local function drawTable(state, message, msgColor)
    term.setBackgroundColor(colors.black)
    term.clear()
    buttons = {}

    centerText(1, "=== CASINO COMPUTERCRAFT ===", colors.yellow)
    centerText(2, "BLACKJACK", colors.white)
    centerText(3, "Points : " .. points, colors.lime)

    if message then
        centerText(4, message, msgColor or colors.white)
    end

    if state ~= "idle" then
        centerText(dealerY - 1, "CROUPIER", colors.lightGray)
        centerText(playerY - 1, "JOUEUR", colors.lightGray)
    end

    if state == "idle" then
        local label = "MISER (" .. MISE .. " point)"
        local bw = #label + 4
        local x1 = math.floor((w - bw) / 2) + 1
        drawButton(1, label, x1, x1 + bw - 1, math.floor(h / 2), colors.green)
    elseif state == "playerTurn" then
        drawButton(1, "TIRER", math.floor(w / 2) - 8, math.floor(w / 2) - 1, h - 1, colors.orange)
        drawButton(2, "RESTER", math.floor(w / 2) + 1, math.floor(w / 2) + 8, h - 1, colors.red)
    end
end

-- === TOUR DU CROUPIER ===
local function dealerPlay(dealerHand, playerHand)
    while handValue(dealerHand) < 17 do
        sleep(0.8)
        table.insert(dealerHand, drawFromDeck())
        drawTable("reveal")
        drawHand(dealerHand, dealerY, false)
        drawHand(playerHand, playerY, false)
    end
end

-- === RESULTAT ===
local function resolveRound(playerHand, dealerHand, playerBJ, dealerBJ)
    local pVal = handValue(playerHand)
    local dVal = handValue(dealerHand)
    local gain, msg, msgColor

    if pVal > 21 then
        gain, msg, msgColor = 0, "BUST ! Tu as perdu.", colors.red
    elseif playerBJ and dealerBJ then
        gain, msg, msgColor = MISE, "Double blackjack, egalite.", colors.yellow
    elseif playerBJ then
        gain, msg, msgColor = MISE * 3, "BLACKJACK ! +" .. (MISE * 3), colors.lime
    elseif dealerBJ then
        gain, msg, msgColor = 0, "Blackjack du croupier... perdu.", colors.red
    elseif dVal > 21 then
        gain, msg, msgColor = MISE * 2, "Le croupier saute ! +" .. (MISE * 2), colors.lime
    elseif pVal > dVal then
        gain, msg, msgColor = MISE * 2, "GAGNE ! +" .. (MISE * 2), colors.lime
    elseif pVal < dVal then
        gain, msg, msgColor = 0, "Perdu... reessaie !", colors.red
    else
        gain, msg, msgColor = MISE, "Egalite, mise remboursee.", colors.yellow
    end

    points = points + gain
    return msg, msgColor
end

-- === UNE MANCHE ===
local function playRound()
    if points < MISE then
        drawTable("idle", "PLUS ASSEZ DE POINTS !", colors.red)
        sleep(2)
        return
    end
    points = points - MISE

    local playerHand, dealerHand = {}, {}
    table.insert(playerHand, drawFromDeck())
    table.insert(dealerHand, drawFromDeck())
    table.insert(playerHand, drawFromDeck())
    table.insert(dealerHand, drawFromDeck())

    local playerBJ = handValue(playerHand) == 21
    local dealerBJ = handValue(dealerHand) == 21

    if playerBJ or dealerBJ then
        drawTable("reveal")
        drawHand(dealerHand, dealerY, false)
        drawHand(playerHand, playerY, false)
        local msg, msgColor = resolveRound(playerHand, dealerHand, playerBJ, dealerBJ)
        centerText(h - 1, msg, msgColor)
        sleep(2.5)
        return
    end

    -- tour du joueur
    while true do
        drawTable("playerTurn")
        drawHand(dealerHand, dealerY, true)
        drawHand(playerHand, playerY, false)
        centerText(playerY - 2, "Total : " .. handValue(playerHand), colors.white)

        local event, side, x, y = os.pullEvent("monitor_touch")
        local action = nil
        for _, btn in pairs(buttons) do
            if x >= btn.x1 and x <= btn.x2 and y == btn.y then
                action = btn.name
                break
            end
        end

        if action == "TIRER" then
            table.insert(playerHand, drawFromDeck())
            if handValue(playerHand) > 21 then
                drawTable("reveal")
                drawHand(dealerHand, dealerY, false)
                drawHand(playerHand, playerY, false)
                local msg, msgColor = resolveRound(playerHand, dealerHand, false, false)
                centerText(h - 1, msg, msgColor)
                sleep(2.5)
                return
            end
        elseif action == "RESTER" then
            break
        end
    end

    -- tour du croupier
    drawTable("reveal")
    drawHand(dealerHand, dealerY, false)
    drawHand(playerHand, playerY, false)
    sleep(0.5)
    dealerPlay(dealerHand, playerHand)

    local msg, msgColor = resolveRound(playerHand, dealerHand, false, false)
    centerText(h - 1, msg, msgColor)
    sleep(2.5)
end

-- === PROGRAMME PRINCIPAL ===
buildDeck()
drawTable("idle")

while true do
    local event, side, x, y = os.pullEvent("monitor_touch")
    for _, btn in pairs(buttons) do
        if x >= btn.x1 and x <= btn.x2 and y == btn.y and btn.name:find("MISER") then
            playRound()
            drawTable("idle")
            break
        end
    end
end